/**
 * 
 */
package tk.redbluelotto.authentication;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import tk.redbluelotto.model.User;
import tk.redbluelotto.service.UserService;

/**
 * 用户身份验证器
 * 
 * @author zb
 * 
 */
public class GlobalAuthenticationProvider implements AuthenticationProvider {

	private UserService userService;
	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
	public GlobalAuthenticationProvider(UserService userService) {
		this.userService = userService;
	}

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		User profile = userService.getUserByUsername(authentication.getPrincipal().toString());

		if (profile == null)
			throw new UsernameNotFoundException(String.format("Invalid credentials", authentication.getPrincipal()));

		if (!profile.getPassword().equals(passwordEncoder.encodePassword((String) authentication.getCredentials(), profile.getUsername())))
			throw new BadCredentialsException("Invalid credentials");

		UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(profile, null, profile.getAuthorities());

		return token;
	}

	@Override
	public boolean supports(Class<?> aClass) {
		return aClass.equals(UsernamePasswordAuthenticationToken.class);
	}
}
